package com.wangfugui.mybatisplus.common.utils;

import com.wangfugui.mybatisplus.common.CommonErrorCode;
import com.wangfugui.mybatisplus.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

@Slf4j
public class FileUtil {
    private static final String SPOT = ".";
    public static void delTempFile(Path path) {
        try {
            Files.deleteIfExists(path);
        } catch (IOException e) {
            log.error("delTempFile() path= {}, error= {}", path, e.getMessage());
        }
    }


    public static String UuidFileName(String fileExt) {
        try {
            StringBuilder filenameBuilder = new StringBuilder();
            filenameBuilder.append("upload_");
            filenameBuilder.append(IdUtils.genUuid());
            filenameBuilder.append(SPOT);
            filenameBuilder.append(fileExt);
            return filenameBuilder.toString();
        } catch (Exception e) {
            log.error("get secureRandom Instance failed!, e: {}", e.getMessage());
        }
        return StringUtils.EMPTY;
    }


    public static String getTempDir(String tempDir) {
        File file = new File(StringUtils.trimToEmpty("F:\\temp"));
        if (System.getProperty("os.name").toLowerCase().contains("windows")) {
            String property = System.getProperty("user.dir");
            String dir = property + "/market-cms/src/main/resources/temp";
            file = new File(dir);
        }

        if (!file.exists()) {
            boolean result = file.mkdirs();
            if (!result) {
                throw new BusinessException(CommonErrorCode.BUSINESS_ERROR.getCode(), "创建临时目录失败!");
            }
        }
        return file.getPath();
    }
}
